package com.mxl.service.cashorder.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.mxl.common.BeanConvertUtil;
import com.mxl.common.StringUtil;
import com.mxl.common.helper.ResponseErrorCode;
import com.mxl.common.rule.RuleEngine;
import com.mxl.dao.cashorder.GatewayRequestDao;
import com.mxl.dao.cashorder.impl.GatewayResponseDaoImpl;
import com.mxl.dao.cashorder.model.GatewayRequest;
import com.mxl.dao.cashorder.model.GatewayResponse;
import com.mxl.service.cashorder.GatewayDispatchService;
import com.mxl.service.cashorder.dto.CashOrderRequest;

@Service("gatewayDispatchService")
public class GatewayDispatchServiceImpl implements GatewayDispatchService {
	private static final Logger logger = LoggerFactory
			.getLogger(GatewayDispatchServiceImpl.class);

	@Resource(name = "gatewayResponseDao")
	private GatewayResponseDaoImpl gatewayResponseDao;
	
	@Resource(name = "gatewayRequestDao")
	private GatewayRequestDao gatewayRequestDao;
	
	@Resource(name = "gatewayRequestCheckEngine")
	private RuleEngine gatewayRequestCheckEngine;

	public void dispatch(CashOrderRequest dto) {
		GatewayRequest model = (GatewayRequest) BeanConvertUtil.convert(
				GatewayRequest.class, dto, new String[] { "customMerchant"});
		logger.info("GatewayDispatchServiceImpl Start......." + dto.toString());
		// 如果是直连则解密卡号卡密
		gatewayRequestDao.saveRequest(model);
		dto.setRequestId(model.getId());
		// 针对接口参数一一校验
		try {
			gatewayRequestCheckEngine.processRequest(dto);
		} catch (Exception e) {
			dto.setMsgId(ResponseErrorCode.FAIL.getValue());
			logger
					.error(
							"GatewayDispatchServiceImpl gatewayRequestCheckEngine fail----membercode orderId:"
									+ dto.getOrderId(), e);

		}
		logger.info("GatewayDispatchServiceImpl end.......requestId:"
				+ dto.getRequestId() + "---------errorCode:" + dto.getMsgId());
		// 保持响应 --如果是直连 并且有错误才保存响应
		if (!StringUtil.isEmpty(dto.getMsgId())) {
			gatewayResponseDao.save(convert(dto));
		} else {
			dto.setMsgId(ResponseErrorCode.SUCC.getValue());
		}
	}

	private GatewayResponse convert(CashOrderRequest dto) {
		GatewayResponse res = new GatewayResponse();
		res.setCreationdate(new Date());
		res.setErrorcode(dto.getMsgId());
		res.setRequestid(dto.getRequestId());
		return res;
	}
}
